package com.estate.shiro;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.estate.pojo.User;
import com.estate.service.user.UserService;

@Service
public class UserRealm extends AuthorizingRealm {
	
	@Autowired
	private UserService userService;

	// 设置realm的名称
	@Override
	public void setName(String name) { 
		super.setName("userRealm");
	}

	// 用于授权
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		return null;
	}

	// 用于认证登录
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
			throws AuthenticationException { 
		// 第一步从token中取出用户名   token是用户输入的用户名和密码
		String user_name = (String) token.getPrincipal();
		// 第二步：根据用户输入的userName从数据库查询
		User user = null;
		try {
			user = userService.findUserByUserName(user_name);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		// 如果查询不到返回null
		if (user == null) {//
			return null;
		}
		// 从数据库查询到密码
		String password = user.getUserPassword();
		// 盐
		String salt = user.getSalt();
		// 将User设置simpleAuthenticationInfo
		SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
				user,password,
				this.getName()); 
		return simpleAuthenticationInfo;
	}

}
